using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using Commerce.Common;

public partial class Install_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    string GetConnString(string tableName)
    {
        string sCString = "Server=" + txtServer.Text + ";Initial Catalog="+tableName+";";
        if (chkTrusted.Checked)
        {
            sCString += "Integrated Security=true;";
        }
        else
        {
            sCString += "user id=" + txtUsername.Text + "; Password=" + txtPassword.Text + ";";

        }
        return sCString;

    }
    void BindDBList()
    {
        //get the list of DBs from the username bits
        using (SqlConnection conn = new SqlConnection()) 
        {

            //the DBList query
            string sql = "SELECT * FROM sysdatabases WHERE name NOT IN ('master','tempdb','model','msdb') ORDER BY [NAME]";

            conn.ConnectionString = GetConnString("master");

            try
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        ddlDB.DataSource = rdr;
                        ddlDB.DataTextField = "name";
                        ddlDB.DataValueField = "name";
                        ddlDB.DataBind();

                        rdr.Close();
                    }
                }
            }
            catch (Exception x)
            {
                ResultMessage1.ShowFail(x.Message);
            }
        }
    }
    protected void chkTrusted_CheckedChanged(object sender, EventArgs e)
    {
        pnlSqlMode.Visible = !chkTrusted.Checked;
    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        //get the list of DBs from the username bits
        using (SqlConnection conn = new SqlConnection())
        {

            //the DBList query
            string sql = "CREATE DATABASE " + txtCreateDB.Text+" COLLATE SQL_Latin1_General_CP1_CI_AS";

            conn.ConnectionString = GetConnString("master");

            try
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.ExecuteNonQuery();

                    BindDBList();

                    //select the one that was just created
                    ddlDB.SelectedValue = txtCreateDB.Text;
                }
            }
            catch (Exception x)
            {
                string sMessage = x.Message;
                if (x.Message.Contains("permission denied"))
                {
                    sMessage = "The account that you're connecting to SQL Server with is not allowed to create a Database. " +
                        "To correct this, you can use SQL Authentication, or you can manually create your database using " +
                        "the SQL Management Studio Express. If you don't have this, you can download it from Microsoft";
                }

                ResultMessage1.ShowFail(sMessage);
            }
        }
    }
    protected void btnSetServer_Click(object sender, EventArgs e)
    {
        BindDBList();
        pnlDB.Visible = true;
        pnlInstall.Visible = true;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        pnlServer.Visible = false;
        pnlDB.Visible = false;
        pnlInstall.Visible = false;

        //get the scripts from the InstallScripts directory
        string scriptPath = Server.MapPath("~/Install/InstallScripts");
        
        //All scripts, including membership are in the above directory
        //altered by Spook, 10/28/2006
        string[] scripts=Directory.GetFiles(scriptPath);
        lblProgress.Text = "<h4>Installing CSK 2.0 Database into Server "+txtServer.Text+"; Database "+ddlDB.SelectedValue+"...</h4>";

		string cskCnctString = GetConnString(ddlDB.SelectedValue); 
		using (SqlConnection conn = new SqlConnection(cskCnctString))
		{

            bool haveError = false;
            
            //open the database.  
			try
			{
				conn.Open();
			}
			catch
			{
				ResultMessage1.ShowFail("Cannot open the database using the credentials you supplied. If you are using a Trusted " +
					"Connection, this is because you have not given the ASP.NET worker process the right priviliges to your database. " +
					"Please <a href=help.aspx>READ THIS first</a>.");
                haveError = true;
				return; 
			}

			//run CSK Scripts
			try{
				RunScriptFiles(scripts, conn);
			}
			catch(Exception ex)
			{
				ResultMessage1.ShowFail("Could not add the CommerceServerKit objects to the selected CSK Database.<br> " +
					"Connection String:" + cskCnctString + "<BR>" + 
					"The following error occurred:<br>" +
					ex.Message);
                haveError = true;
                return; 
			}

			//Set web.config file
			try{
				SetWebConfig(); 
			}
			catch (Exception ex){
				ResultMessage1.ShowFail("Could not updatethe CommerceServerKit web.config file with the correct settings.<br> " +
					"Please update the CSK web.config file manually. <BR>" + 
					"The following error occurred:<br>" + ex.Message);
                haveError = true;
                return; 
			}

            if (!haveError)
                Response.Redirect("~/default.aspx", true);

		}

    }

	private void RunScriptFiles(string[] scripts, SqlConnection conn)
	{		
			using (SqlCommand cmd = new SqlCommand("", conn))
			{
				foreach (string script in scripts)
				{
				  RunStatements(cmd, script);

				}

			}
		
	}

	private void RunStatements(SqlCommand cmd, string script)
	{
		string[] statements = GetExecutionPlan(script);
		foreach (string statement in statements)
		{
			string sql = statement;
			try
			{
				cmd.CommandText = sql;
				cmd.ExecuteNonQuery();
			}
			catch (Exception x)
			{
				string sMessage = x.Message;
				if (sMessage.ToLower().Contains("permission denied"))
					sMessage = "Your login does not have permission to create schema on your server. Make sure " +
						"that the login information you are using has EXECUTE and CREATE permissions (dbowner) for your SQL " +
						" Server.";
				ResultMessage1.ShowFail(x.Message);
				throw;
			}
		}
	}

    void SetWebConfig()
    {
        string configPath = Server.MapPath("~/Web.Config");
        string sConfig = Utility.GetFileText("../Web.Config");

        //write them back
        Utility.UpdateFileText(configPath, "STOREDATASOURCEUNSET", GetConnString(ddlDB.SelectedValue).Replace("&", "&amp;"));
        Utility.UpdateFileText(configPath, "MEMBERSHIPDATASOURCEUNSET", GetConnString(ddlDB.SelectedValue).Replace("&", "&amp;"));
    }

    private string[] GetExecutionPlan(string filePath)
    {

        string sql = Utility.GetFileText(filePath);
        string[] SqlLine;
        Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);

        SqlLine = regex.Split(sql);

        return SqlLine;
    }

}
